﻿
from django.shortcuts import HttpResponse

import json
from django.core.cache import cache

try:

    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object  # Django 1.4.x - Django 1.9.x


# 防止重复提交请求
class PreventDuplicateMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print('request.method', request.method)
        if request.method == 'POST':
            params = json.loads(request.body)
            print('params', params)
            if 'noncestr' in params:
                flag = cache.get(params['noncestr'])
                if flag is None:
                    # flag 为空 放入标识 60秒后过期
                    cache.set(params['noncestr'], params['noncestr'], 120)
                    pass
                else:
                    data = {'status': 401, 'msg': '请勿重复提交请求'}
                    return HttpResponse(json.dumps(data))
